package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import Bean.Car;
import Bean.User;
import sql.JDBCUtil;

public class CarDao {
	public Car selectByCar_id(String car_id) throws Exception {
		Car car = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		Connection con = null;
		String sql = "select * from car where car_id= ?;";
		try {
			con = JDBCUtil.getcon();
			ps = con.prepareStatement(sql);
			ps.setString(1, car_id);
			rs = ps.executeQuery();
			if(rs.next()) {
				car = new Car();
				car.setCar_id(rs.getString("car_id"));
				car.setCreateTime(rs.getString("createTime"));
			}
		} catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtil.close(rs, ps, con);
		}
		return car;
	}
	public List<Car> selectAllCar() throws Exception {
		List<Car> list = new ArrayList<Car>();
		Car car = null;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from car;";
		try {
			con = JDBCUtil.getcon();
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				car = new Car();
				car.setCar_id(rs.getString("car_id"));
				car.setCreateTime(rs.getString("createTime"));
				list.add(car);
			}
		} catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtil.close(rs, ps, con);
		}
		return list;
	}
	public List<Car> selectByCreateTime(String createTime) throws Exception {
		List<Car> list = new ArrayList<Car>();
		Car car = null;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from car where DATE(createTime) = ?;";
		try {
			con = JDBCUtil.getcon();
			ps = con.prepareStatement(sql);
			ps.setString(1, createTime);
			rs = ps.executeQuery();
			while(rs.next()) {
				car = new Car();
				car.setCar_id(rs.getString("car_id"));
				car.setCreateTime(rs.getString("createTime"));
				list.add(car);
			}
		} catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtil.close(rs, ps, con);
		}
		return list;
	}
	public void insert(Car car) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		String sql = "insert into car value(?, null);";
		try {
			con = JDBCUtil.getcon();
			ps = con.prepareStatement(sql);
			ps.setString(1, car.getCar_id());
			ps.executeUpdate();
		} catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtil.close(null, ps, con);
		}
	}
	public void dropByCarId(String car_id) throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		String sql = "delete from car where car_id = ?";
		try {
			con = JDBCUtil.getcon();
			ps = con.prepareStatement(sql);
			ps.setString(1, car_id);
			ps.executeUpdate();
		} catch(SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtil.close(null, ps, con);
		}
	}
	
}
